package com.rz.htk.order.controller;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.itextpdf.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import com.rz.core.kit.RespKit;
import com.rz.core.resp.ResultResp;
import com.rz.htk.order.entity.Order;
import com.rz.htk.order.entity.vo.OrderDeleteParam;
import com.rz.htk.order.entity.vo.OrderImportParam;
import com.rz.htk.order.entity.vo.PrintParam;
import com.rz.htk.order.entity.vo.ZyPdfReq;
import com.rz.htk.order.service.IOrderService;
import com.rz.htk.order.task.OrderTask;
import com.rz.htk.print.util.PDFUtil;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private IOrderService IOrderService;
    @Resource
    private OrderTask orderTask;

    @PostMapping("/getPage")
    public ResultResp getPage(@RequestBody Order order) {
        return RespKit.success(IOrderService.getPage(order));
    }

    @PostMapping("/getSimplePage")
    public ResultResp getSimplePage(@RequestBody Order order) {
        return RespKit.success(IOrderService.getSimplePage(order));
    }

    @PostMapping("/saveOrder")
    public ResultResp saveOrder(@RequestBody Order order) {
        return RespKit.success(IOrderService.saveOrder(order));
    }


    @PostMapping("/saveOrderMessage")
    public ResultResp saveOrderMessage(@RequestBody OrderDeleteParam orderDeleteParam) {
        return RespKit.success(IOrderService.saveOrderMessage(orderDeleteParam));
    }

    @PostMapping("/saveOrderGetCode")
    public ResultResp saveOrderGetCode(@RequestBody Order order, HttpServletRequest request) {
        Object crteMngIdObj = request.getAttribute("crteMngId");
        if (crteMngIdObj != null) {
            order.setCrteMngId(Integer.valueOf(crteMngIdObj.toString()));
        }
        ResultResp resultResp = IOrderService.saveOrderGetCode(order);
        return resultResp;
    }

    @PostMapping("/batchDelete")
    public ResultResp batchDelete(@RequestBody OrderDeleteParam orderDeleteParam) {
        return RespKit.success(IOrderService.batchDelete(orderDeleteParam));
    }

    /**
     * 修改订单状态
     *
     * @param orderDeleteParam
     * @param
     * @return
     */
    @PostMapping("/updateOrderState")
    public ResultResp updateOrderState(@RequestBody OrderDeleteParam orderDeleteParam) {
        return RespKit.success(IOrderService.updateOrderState(orderDeleteParam));
    }

    @PostMapping("/updateOrderOut")
    public ResultResp updateOrderOut(@RequestBody OrderDeleteParam orderDeleteParam) {
        return RespKit.success(IOrderService.updateOrderOut(orderDeleteParam));
    }

    @PostMapping("/updateOrderStateByAfterCode/{afterCode}/{status}")
    public ResultResp updateOrderStateByAfterCode(@PathVariable String afterCode,@PathVariable Integer status) {
        return RespKit.success(IOrderService.updateOrderStateByAfterCode(afterCode,status));
    }

    @PostMapping("getOrderById/{orderId}")
    public ResultResp getOrderById(@PathVariable Integer orderId) {
        return RespKit.success(IOrderService.getOrderById(orderId));
    }

    @PostMapping("getOrderByAfterCode/{afterCode}")
    public ResultResp getOrderByAfterCode(@PathVariable String afterCode) {
        Order order = IOrderService.getOrderByAfterCode(afterCode);
        if (order == null) {
            order = IOrderService.getOrderByAfterCode(afterCode.substring(8));
        }
        return RespKit.success(order);
    }

    /**
     * 导入订单
     *
     * @return
     */
    @PostMapping("/importOrder")
    public ResultResp importOrder(MultipartFile file, OrderImportParam orderImportParam) throws IOException {
        return RespKit.success(IOrderService.importOrderExcel(file, orderImportParam.getCrteMngId(), orderImportParam.getConsumerCode(),orderImportParam.getType()));
    }

    @PostMapping("/exportOrder")
    public void exportOrder(@RequestBody Order order, HttpServletResponse response) throws IOException {
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=temp.xls");
        response.setContentType("application/msexcel");
        IOrderService.exportOrder(order, output);
        output.flush();
        output.close();
    }

    @PostMapping("/exportPrintTemplate")
    public void exportPrintTemplate(@RequestBody OrderDeleteParam orderDeleteParam, HttpServletResponse response) throws IOException, DocumentException {
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "inline; filename=PrintTemp.pdf");
        response.setContentType("application/pdf");
        IOrderService.getByOrderIds(orderDeleteParam.getIds(), output);
        output.flush();
        output.close();
    }

    @PostMapping("/testTask")
    public void testTask(@RequestBody Order order, HttpServletResponse response) throws IOException {
        orderTask.getPGSTracks(order.getAfterCode());
    }

    @PostMapping("pushOrderToDaRong/{orderId}")
    public ResultResp pushOrderToDaRong(@PathVariable Integer orderId) {
        Order order = IOrderService.getOrderById(orderId);
        List<Order> orderList = new ArrayList<>();
        orderList.add(order);
        orderTask.pushOrderToDaRong(orderList);
        return RespKit.success(null);
    }

    @PostMapping("countOrderTotal/{adminId}")
    public ResultResp countOrderTotal(@PathVariable Integer adminId) {
        return RespKit.success(IOrderService.countOrderTotal(adminId));
    }

    @NacosValue(value = "${enableScheduled}", autoRefreshed = true)
    private boolean enableScheduled;

    @GetMapping("getNacos")
    public ResultResp getNacos() {
        return RespKit.success(enableScheduled);
    }

    @PostMapping("orderReceiveBack/{orderId}")
    public ResultResp orderReceiveBack(@PathVariable Integer orderId) throws Exception {
        return RespKit.success(IOrderService.orderReceiveBack(orderId));
    }

    @PostMapping("downloadTemplateByOrder")
    public void downloadTemplateByOrder(@RequestBody ZyPdfReq zyPdfReq, HttpServletResponse httpResponse) throws IOException {
        httpResponse.reset();
        ServletOutputStream outputStream = httpResponse.getOutputStream();
        IOrderService.downloadTemplateByOrder(zyPdfReq.getOrderIds(),outputStream);
    }

    @PostMapping("downloadTemplateByAfterCode")
    public void downloadTemplateByAfterCode(@RequestBody ZyPdfReq zyPdfReq,HttpServletResponse httpResponse) throws IOException {
        httpResponse.reset();
        ServletOutputStream outputStream = httpResponse.getOutputStream();
        IOrderService.downloadTemplateByAfterCode(zyPdfReq.getAfterCodes(),outputStream);
    }

    @PostMapping("print")
    public ResultResp print(@RequestBody PrintParam printParam){
        return RespKit.success(IOrderService.print(printParam));
    }

    @PostMapping("exportPdfByAfterCodes")
    public void exportPdfByAfterCodes(@RequestBody List<String> orderCodes, HttpServletResponse response) throws IOException, com.lowagie.text.DocumentException {
        OutputStream output = response.getOutputStream();
        List<Order> orderList =  IOrderService.exportPdfByHtml(orderCodes);
        if(orderList.size() > 0){
            ITextRenderer render = PDFUtil.createPdf(output,orderList.get(0),false);
            for (int i = 1; i < orderList.size(); i++) {
                Order order = orderList.get(i);
                String content = PDFUtil.freeMarkerRender(order);
                render.setDocumentFromString(content);
                render.layout();
                render.writeNextDocument();
            }
            render.finishPDF();
            response.setHeader("Content-disposition", "inline; filename=PrintTemp.pdf");
            response.setContentType("application/pdf");
            output.flush();
            output.close();
        }
    }

}
